package util.android.sqlite;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import util.www.sql.SelectSql;

public class SelectSQLite<T>
extends SelectSql
{
	private final Class<T> claseParaInstanciar;
	//private String sql;//no usar. Mejor usar SQLiteUtil.executeQuery(...,sql,...)
	
	private SeteadorSQLite<T> seteador;

	public SelectSQLite(Class<T> claseParaInstanciar) {
		this.claseParaInstanciar = claseParaInstanciar;
	}

	public SelectSQLite<T> setSelect() {
		return this;
	}
	
	public SelectSQLite<T> setSeteador(SeteadorSQLite<T> seteador) {
		this.seteador = seteador;
		return this;
	}

	public T getUnique(SQLiteOpenHelper openHelper) throws SQLException {		
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = null;
		try {
			cursor = db.rawQuery(this.getSql(), null);
			if(cursor.moveToNext()) {
				T obj = claseParaInstanciar.newInstance();
				seteador.ejecutar(cursor, obj);
				return obj;
			}
		}
		catch(Exception ex) {
			throw new SQLException(ex);
		}
		finally {			
			if(cursor!=null) cursor.close();
			if(db!=null) db.close();
		}
		return null;
	}

	public List<T> getLista(SQLiteOpenHelper openHelper) throws SQLException {
		List<T> lista = new ArrayList<T>();
		
		SQLiteDatabase db = openHelper.getReadableDatabase();
		Cursor cursor = null;
		try {
			cursor = db.rawQuery(this.getSql(), null);
			while(cursor.moveToNext()) {
				T obj = claseParaInstanciar.newInstance();
				seteador.ejecutar(cursor, obj);
				lista.add(obj);
			}
		}
		catch(Exception ex) {
			throw new SQLException(ex);
		}
		finally {			
			if(cursor!=null) cursor.close();
			if(db!=null) db.close();
		}
		return lista;
	}
	
}
